package cn.com.klun.tjy.utils;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 指定文件下载
 * 获取某路径下所有文件名
 * 删除制定文件
 * 
 * @author Muxb
 *
 */
@Component
public class FtpTools {

	private static Logger logger = Logger.getLogger(FtpTools.class);

	private final static String name = "ftp.name";
	private final static String pwd = "ftp.password";
	private final static String url = "ftp.url";
	private final static String port = "ftp.port";
	private final static String path = "ftp.import.path";
	private final static String dataTimeout = "ftp.DataTimeout";
	private final static String defaultTimeout = "ftp.DefaultTimeout";
	
	private FTPClient ftpClient;
	//private boolean flag = true;
	  
	public void reSet() {
		// TODO 复位的参数
	  //this.connectServer(Global.getGlobalConf(url), Integer.parseInt(Global.getGlobalConf(port)), Global.getGlobalConf(name), Global.getGlobalConf(pwd), Global.getGlobalConf(path)+new SimpleDateFormat("yyyyMMdd").format(new Date()),Integer.valueOf(Global.getGlobalConf(dataTimeout)),Integer.valueOf(Global.getGlobalConf(defaultTimeout)));
	}   
	
	/**
	 * ftp服务连接信息
	 * 
	 * @param ftpUrl
	 * @param ftpPort
	 * @param ftpName
	 * @param ftpPwd
	 * @param ftpImportPath
	 */
	public void connectServer(String ftpUrl, int ftpPort, String ftpName, String ftpPwd, String ftpImportPath,int dataTimeout,int defaultTimeout) {   
		  ftpClient = new FTPClient();   
		  try {  
			//传输的字符编码(防乱码)  
			ftpClient.setControlEncoding("UTF-8");
			
			//设置linux环境
			FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
			ftpClient.configure(conf);
			
		    //超时时间(防止FTP僵死)
			ftpClient.setDataTimeout(1000 * dataTimeout);
			ftpClient.setDefaultTimeout(1000 * defaultTimeout);

			//被动模式
			ftpClient.enterLocalPassiveMode();
		    //工作流的大小  
			ftpClient.setBufferSize(1024 * 4);

			// 连接   
			ftpClient.connect(ftpUrl, ftpPort); 
			
			if(ftpClient.isConnected()){
			   // 登录   
			   if(ftpClient.login(ftpName, ftpPwd)){
				   if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){ 
					   if (ftpImportPath != null && ftpImportPath.length() > 0) { 
						   logger.info("--log--FtpTools.connectServer() 连接ftp服务器 "+ftpUrl+" 成功 ,当前目录" +ftpClient.printWorkingDirectory());
						   ftpClient.setSoTimeout(1000 * defaultTimeout);
						   // 跳转到指定目录   
						   //if(!ftpClient.changeWorkingDirectory(ftpImportPath))flag = false;
						   ftpClient.changeWorkingDirectory(ftpImportPath);
					   }
				   }
			   }
			}
		  } catch (SocketException e) {   
			  logger.error("--log--FtpTools.connectServer() 连接ftp服务器异常 {}",e);
		  } catch (IOException e) {   
			  logger.error("--log--FtpTools.connectServer() 连接ftp服务器异常 {}",e);
		  }   
	}   
	  
	/**
	 * 关闭连接   
	 */
	public void closeServer() {   
	  if (ftpClient.isConnected()) {   
		 try {   
		   //ftpClient.logout();   
		   ftpClient.disconnect();
		 } catch (IOException e) {   
			 e.printStackTrace();   
		 }   
	  }   
	}   
	  
	/**
	 * 读取指定路径下的文件名
	 * @param
	 * @return
	 */
	public List<String> getFileList() {
		List<String> fileLists = new ArrayList<String>();
		// 获得指定目录下所有文件名   
		FTPFile[] ftpFiles = null;   
		try {
			logger.info("--log--FtpTools.connectServer() 连接ftp服务器 127 当前目录" +ftpClient.printWorkingDirectory());
			//if(!flag) return fileLists;
			ftpFiles = ftpClient.listFiles();
			
			  if (ftpFiles != null && ftpFiles.length > 0) {
				  logger.info("ftpClient.listFiles()");
				  for (FTPFile f : ftpFiles) {
					  logger.info(f.getName());
				  }

			  }
		} catch (IOException e) {
			logger.error("--log--FtpTools.getFileList() 获取文件名异常 {}", e);
		}   
			
		  for (int i = 0; ftpFiles != null && i < ftpFiles.length; i++) {
			   FTPFile file = ftpFiles[i];
			   if (file.isFile()) {  
				   logger.info("file name: " + file.getName());
				   fileLists.add(file.getName());   
			   }   
		  }   

		  return fileLists;
	}

	/**
	 * 读取指定路径下的文件名
	 * @param
	 * @return
	 */
	public List<String> getFileListA(String a) {   
	  List<String> fileLists = new ArrayList<String>();   
	  // 获得指定目录下所有文件名   
	  FTPFile[] ftpFiles = null;   
	  try {   
		  ftpFiles = ftpClient.listFiles(a);
	  } catch (IOException e) {   
	   e.printStackTrace();   
	  }   
	  for (int i = 0; ftpFiles != null && i < ftpFiles.length; i++) {
		   FTPFile file = ftpFiles[i];   
		   if (file.isFile()) {   
			   fileLists.add(file.getName());   
		   }   
	  }   
	  return fileLists;   
	}
	
	public InputStream retrieveFileStream(String fileName) throws IOException{
		return ftpClient.retrieveFileStream(fileName);
	}
	
	public void completePendingCommand() throws IOException{
		//告诉ftp这个文件流传输完毕的状态
		ftpClient.completePendingCommand();
	}
	
	/**
	 *  在服务器读取指定文件，返回List<Map<String,Object>>
	 *  
	 * @param fileName
	 * @return List<Map<String,Object>>
	 * @throws ParseException
	 * @throws IOException 
	 */
	public List<Map<String,Object>> readFile(String fileName) throws ParseException, IOException {
		InputStream ins = null;
		BufferedReader reader = null;
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		list.clear();
		try{
			logger.info("--log--FtpTools.readFile() 文件名  "+fileName+"  当前目录 " +ftpClient.printWorkingDirectory()+" 连接状态："+ftpClient.isConnected() +" 线程 ："+Thread.currentThread().getName());
			// 从服务器上读取指定的文件   
			ins = ftpClient.retrieveFileStream(fileName);
			if(null != ins && ins.available() > 0){
				reader = new BufferedReader(new InputStreamReader(ins, "UTF-8"));   
				String line = null;
				while ((line = reader.readLine()) != null) {
					Map<String,Object> map = JSON.parseObject(line);
					list.add(map);
				}
				
			}
		}finally{
			if(reader != null && ins != null){
				reader.close();
				ins.close();
			}
			//告诉ftp这个文件流传输完毕的状态
			ftpClient.completePendingCommand();
		}
		return list;
	}   
	
	/**
	 *  在服务器读取指定文件,返回字符串
	 *  
	 * @param fileName
	 * @return String
	 * @throws ParseException
	 */
	public String readFileString(String fileName) throws ParseException {   
	  InputStream ins = null;   
	  StringBuffer sb = new StringBuffer();
	  try {   
		   // 从服务器上读取指定的文件   
		   ins = ftpClient.retrieveFileStream(fileName);  
		   if(null != ins && ins.available() > 0){
			   BufferedReader reader = new BufferedReader(new InputStreamReader(ins, "UTF-8"));   
			   String line;   
			   while ((line = reader.readLine()) != null) {   
				   sb.append(line);
			   }
			   reader.close();  
			   ins.close();  
			   return sb.toString();
		   }
	  } catch (IOException e) {   
		  e.printStackTrace();   
	  }   
	  return null;
	}   
	
	/**
	 * 删除指定文件 
	 * @param fileName
	 */
	public void deleteFile(String fileName) {   
	  try {   
		  ftpClient.deleteFile(fileName);   
	  } catch (IOException e) {   
	   e.printStackTrace();   
	  }   
	}   
	
	private String pwd(){
		try {
			return ftpClient.printWorkingDirectory();
			//return ftpClient.pwd();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public static void main(String[] args) {
		FtpTools ftp = new FtpTools();
		ftp.connectServer("10.150.20.1", 21, "mylc-ftp", "123456", "/20210521",60,60);
		System.out.println("-------------"+ftp.pwd());
//		boolean dirExist = ftp.isDirExist("/20171016");
//		System.out.println("------------>"+dirExist);
		//读取指定文件名
//		String readFile;
//		try {
//			readFile = ftp.readFileString("20210521-T8001-01-info-1.txt");
//			System.out.println(readFile);
//		} catch (ParseException e) {
//			e.printStackTrace();
//		}
		//读取目录下所有文件
//		List<String> fileList = ftp.getFileListA("/20210521");
//		for (int i = 0; i < fileList.size(); i++) {
//			System.out.println(fileList.get(i));
//		}
		//删除文件
		//ftp.deleteFile("test.txt");
		
	}
}
